import { defineStore } from 'pinia'
import router from '@/router'

interface ITabs {
  tabMenuList: ITabMenu[]
  activeTab: string
}

const useTabsStore = defineStore('tabs', {
  state: (): ITabs => {
    return {
      tabMenuList: [
        {
          id: '首页',
          path: '/layout/home',
          title: '首页',
          isClose: false,
        },
      ],
      activeTab: '/layout/home',
    }
  },

  actions: {
    addTabMenuList(tabMenu: ITabMenu) {
      if (this.tabMenuList.every((item) => item.path !== tabMenu.path)) {
        this.tabMenuList.push(tabMenu)
        // 激活tab标签
      }
      this.activeTab = tabMenu.path as string
    },
    removeTabMenu(path: string) {
      // 将仓库中的对应 tabMenuList 删除
      const index = this.tabMenuList.findIndex((item) => item.path == path)
      const tabMenuList = this.tabMenuList
        .slice(0, index)
        .concat(this.tabMenuList.slice(index + 1))
      this.tabMenuList = tabMenuList

      // 不是当前路径删除就直接返回
      if (path !== this.activeTab) {
        return
      }

      console.log(`${this.tabMenuList[index - 1].path}`)

      this.activeTab = this.tabMenuList[index - 1].path as string

      // 是当前路径则转到删除下表的前一位
      router.push(`${this.tabMenuList[index - 1].path}`)
    },
  },
  persist: true,
})

export default useTabsStore
